require "lfs"
require "unity"
local MPIModel = require "MPIModel"
local CreateRadome = require "luaCreateRadome"
local nl = require"luaNumeric"
local QGallop = require"QGMainWindow"
require "Q2DViewer"
local Q2DViewer = require "Q2DViewerEx"


----------------------------------------------------------------------------
--初始化参数
local FSSRadomeDMGenerator={
	console_mode = false;
	p = 10; --频选周期
	nx = {20,40,60};
	xstart=-1400;
	xend=-1000;
	create_str = [[
p = 15;                       --频选周期
nx = {20,40,60};          --分割节点
xstart=-1400;            --贴敷起始位置
xend=-1000;               --贴敷结束位置
		
unitGenerator = function( x,y,z)
	local w=2;
	local l = 8;
	local dw = 0.5;
	local GLShapes = require"luaGLShapes";
	
	local rect1 = GLShapes.create_rect({pt1={0,-w/2.}; pt2={l,w/2.}} );
	local rect2 = rect1:copy();
	rect2:rotate(zAxis,120);
		
	local rect3 = rect1:copy();
	rect3:rotate(zAxis,240);

	local outr = GLShapes.join({rect1,rect2,rect3});
		
	local rect1 = GLShapes.create_rect({pt1={0,-w/2.+dw}; pt2={l-dw,w/2.-dw}} );
	local rect2 = rect1:copy();
	rect2:rotate(zAxis,120);
		
	local rect3 = rect1:copy();
	rect3:rotate(zAxis,240);

	local inr = GLShapes.join({rect1,rect2,rect3});
		
	return GLShapes.difference({outr,inr})
end;

GLShapes = require"luaGLShapes";

mmm = GLShapes.load_step('d:\temp\m.step');	
extUnitGenerator = function( x,y,z)
	--return GLShapes.NewCylinder( {radius=3;height=2; } )
	return mmm;
end;	
extUnitGenerator(0,0,0);


	
	]];
};
-----------------------------------------------------------------------------


-----------------------------------------------------------------------------
---[[创建表和创建元表
function FSSRadomeDMGenerator:new (o)
	o = o or {};
	self.__index = self;	
	setmetatable(o,self)
	self:regist_funcs_to_gallop();
	return o;
end
--]]---------------------------------------------------------------------------


----------------------------------------------------------------------------------------------------------------------------------------
--注册全局函数
function FSSRadomeDMGenerator:regist_funcs_to_gallop()
	Gallop.init_funcs['FSSRadomeDMGenerator'] = function()
		local str = Geometry.get_setting( 'FSSRadomeDMGenerator.Settings' )
		if str ~= '' then
			Geometry.FSSRadomeDMGenerator:set_settings_str(str)
		end
		Geometry.FSSRadomeDMGenerator:update_script_to_ui();
	end;
	
	Gallop.load_funcs['FSSRadomeDMGenerator'] = function()
		local str = Geometry.get_setting( 'FSSRadomeDMGenerator.Settings' )
		if str ~= '' then
			Geometry.FSSRadomeDMGenerator:set_settings_str(str)
		end
		Geometry.FSSRadomeDMGenerator:update_script_to_ui();
	end;
	
	Gallop.presave_funcs['FSSRadomeDMGenerator'] = function()
		Geometry.FSSRadomeDMGenerator:update_script_from_ui()
		local str = Geometry.FSSRadomeDMGenerator:get_settings_str();
		Geometry.set_setting( 'FSSRadomeDMGenerator.Settings', str );
	end;
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--GUI交互函数
function FSSRadomeDMGenerator:update_script_to_ui()
end

function FSSRadomeDMGenerator:update_script_from_ui()
end
----------------------------------------------------------------------------------------------------------------------------------------



function FSSRadomeDMGenerator:create_viewer2D ( )
	return viewer;
end



----------------------------------------------------------------------------------------------------------------------------------------
--打包所有参数
function FSSRadomeDMGenerator:get_settings_str()
	local str = '';
	for k,v in pairs(self) do
		 if type(k) == "string" and (type(v)=="number" or type(v)=="boolean") then
			str = str .. k .. '=' .. tostring(v) .. '; \n'
		 end
		 
		 if type(k) == "string" and ( type(v)=="string"  ) then
			str = str .. k .. '= [[' .. tostring(v) .. ']]; \n'
		 end
	end
	return str;
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--设置所有参数
function FSSRadomeDMGenerator:set_settings_str(str)
	local f = load(' return {' .. str ..'}')
	local sets = f();
	for k,v in pairs(sets) do
		self[k] = v;
	end
end
----------------------------------------------------------------------------------------------------------------------------------------


----------------------------------------------------------------------------------------------------------------------------------------
--运行
function FSSRadomeDMGenerator:perspective_view ()
	-- print('perspective')
	if self.console_mode == false then
		local QGallop = require"QGMainWindow"
		if QGallop~=nil and QGallop.getMainWindow then
			local mw = QGallop.getMainWindow();
			if mw~=nil then
				local view = mw:get3DView();
				if view~=nil then
					view:showEntireScene();
					view:perspective();
				end
			end
		end
	end
end
----------------------------------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------------------------
--设置计算脚本
function FSSRadomeDMGenerator:set_script(script)
	if script ~= self.create_str then
		self.create_str = script;
		 print(self.create_str);
		self:create_model_from_str();
		self:update_script_to_ui();
	end	
end
----------------------------------------------------------------------------------------------------------------------------------------


----------------------------------------------------------------------------------------------------------------------------------------
--设置计算脚本
function FSSRadomeDMGenerator:create_model_from_str()

	function trace (event, line)
	    if GetStopFlag()==true then
		local s = debug.getinfo(2).source
		print( s .. ":" .. line )
		error("abort by user")
	    end
	end

     local f = load(self.create_str)
      f();
       
      self.p = p;      
      self.nx = nx;
      self.xstart = xstart;
      self.xend = xend;
      self.unitGenerator = unitGenerator;
      
     self.extUnitGenerator = extUnitGenerator;
     
    debug.sethook(trace, "l")
end
----------------------------------------------------------------------------------------------------------------------------------------

-----------------------------------------------------------------------------
--导入模型
function FSSRadomeDMGenerator:load ( path )
	Geometry.clear_all();
	self.path = path;
	self.radome = Geometry.load_step(path);
	-- Geometry.AddShape(self.radome)
	self:perspective_view()
	print(path)
	
	-----------------------------------------------------
	-- import the radome model
	self.analyzer = CreateRadome.RadomeDMAnalyzer:new();
	assert(self.analyzer:import_from_file(path)>=0, "import file error!\n"..path );
	-- assert(analyzer:isSolid(), "导入模型不包含实体!" );
	assert(self.analyzer:numSolid()<=1, "导入模型超过一个实体!" );
	 assert(self.analyzer:checkOrientation(), " 天线罩大端未朝向x轴正向" );
	 assert(self.analyzer:decomposite(), " 天线罩面元分析失败！" );
	-- assert(analyzer:decomposite_semi_radome(), " 天线罩面元分析失败！" );
	self.analyzer:intersection_with_xy_plane()
	-- assert(analyzer:regenerate_profile(), "重新生成外表面错误" );
	-- assert(analyzer:regenerate_from_xz_section(), "重新生成外表面错误" );

	-----------------------------------------------------
	


	self:perspective_view()
	


end
-----------------------------------------------------------------------------

-----------------------------------------------------------------------------
--创建锥罩频选结构
function FSSRadomeDMGenerator:generate_outer ( )
		

end
-----------------------------------------------------------------------------

function FSSRadomeDMGenerator:create_cone_fss ( )

	 -- 
	self:update_script_from_ui();
	
	print("p="..self.p);
	print("xstart="..self.xstart);
	 -- self:create_cone_fss();
	 
	local nxsplit = nl.new_ivector( #self.nx )
	for ii=1,#self.nx do
	     nxsplit[ii] = self.nx[ii];
	end
	
	local  tsplit = nl.new_vector();
	-- tsplit :push_back(0);
	-- tsplit :push_back(math.pi/2);
	
	print( "start filling..." )
	self.generator = CreateRadome.FSSRadomeDMGenerator:new(self.p,1e-4);
	self.generator:fss_range(self.xstart,self.xend)
	self.generator:fss_theta_range(0,math.pi)
	-- self.generator:setDn(self.dN or 20)
	self.generator:create_outer( self.analyzer );
	
	self.generator:build_equal_segments_pts_from_curve();
	
	self.generator:split_face_by_period_ndoes(nxsplit,tsplit);	
	
	self.generator:unitGenerator(self.unitGenerator);
	self.generator:extUnitGenerator(self.extUnitGenerator);




	-- self.generator:build_fss_units();
	self.generator:build_external_units();
	
end


-----------------------------------------------------------------------------
--创建分块边界
function FSSRadomeDMGenerator:create_cone_fss1 ( )


	local nxsplit = nl.new_ivector( #self.nx )
	for ii=1,#self.nx do
	     nxsplit[ii] = self.nx[ii];
	end
	
	local  tsplit = nl.new_vector();
	-- tsplit :push_back(0);
	-- tsplit :push_back(math.pi/2);
	
	print( "start filling..." )
	self.generator = CreateRadome.FSSRadomeDMGenerator:new(self.p,1e-4);
	self.generator:fss_range(self.xstart,self.xend)
	self.generator:fss_theta_range(0,math.pi)
	-- self.generator:setDn(self.dN or 20)
	self.generator:create_outer( self.analyzer );
	
	self.generator:build_equal_segments_pts_from_curve();
	
	self.generator:split_face_by_period_ndoes(nxsplit,tsplit);	
	
	
	-- self.generator:create_section_edges();
	-- self.generatorgenerator:set_external_shape( self.objExt );
	 local GLShapes = require"luaGLShapes";


	
	
	local unitGenerator = function( x,y,z)
		local w=2;
		local l = 8;
		local dw = 0.5;
		
		local rect1 = GLShapes.create_rect({pt1={0,-w/2.}; pt2={l,w/2.}} );
		local rect2 = rect1:copy();
		rect2:rotate(zAxis,120);
		
		local rect3 = rect1:copy();
		rect3:rotate(zAxis,240);

		local outr = GLShapes.join({rect1,rect2,rect3});
		
		local rect1 = GLShapes.create_rect({pt1={0,-w/2.+dw}; pt2={l-dw,w/2.-dw}} );
		local rect2 = rect1:copy();
		rect2:rotate(zAxis,120);
		
		local rect3 = rect1:copy();
		rect3:rotate(zAxis,240);

		local inr = GLShapes.join({rect1,rect2,rect3});
		
		return GLShapes.difference({outr,inr})

	end
	
	self.generator:unitGenerator(unitGenerator);




	self.generator:build_fss_units();
	
	self.generator:write_fss( self.path .. "-fss.stp" );
	self.generator:write_cfss( self.path .. "-cfss.stp" );
	self.generator:write_combined_fss( self.path .. "-all.stp" );
	self.generator:write_fss_segments( self.path .. "-fss-segments(%d).stp" );
	self.generator:write_cfss_segments( self.path .. "-cfss-segments(%d).stp" );

end
-----------------------------------------------------

return FSSRadomeDMGenerator;
